package com.gitee.huanminabc.utils_common.string;

import com.gitee.huanminabc.jcommon.file.IoStreamUtil;
import info.monitorenter.cpdetector.io.*;
import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * 简要描述
 *
 * @Author: mac
 * @Date: 2025/4/3 12:30
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
public class StringCodingUtil {

    //字符串编码获取
    public static String getStrCharsetName(String str) throws IOException {
        // 获取 CodepageDetectorProxy 实例
        CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
        // 添加解析器，会使用到添加的后 2 个 ext 里的 jar 包
        detector.add(new ParsingDetector(false));
        detector.add(JChardetFacade.getInstance());
        detector.add(ASCIIDetector.getInstance());
        detector.add(UnicodeDetector.getInstance());
        //字符串转InputStream
        InputStream inputStream = IoStreamUtil.strToInputStream(str);
        Charset charset = detector.detectCodepage(inputStream, str.length());
        if (charset != null) {
            return charset.name();
        } else {
            return null;
        }
    }

    //字符串编码转换
    @SneakyThrows
    public String strTransitionCoding(String str, String oldCoding, String newCoding) {
        return new String(str.getBytes(oldCoding), newCoding);

    }
}
